package jjn.round1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-06-22 12:50
 */
public class Interview_16_19_dfs {
    public int[] pondSizes(int[][] land) {
        int height = land.length;
        int width = land[0].length;
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (land[i][j] == 0) {
                    result.add(dfsForSize(land, i, j));
                }
            }
        }
        return result.stream().sorted().mapToInt(i -> i).toArray();
    }
    
    private int dfsForSize(int[][] land, int i, int j) {
        if (i < 0 || j < 0 || i >= land.length || j >= land[0].length || land[i][j] != 0) {
            return 0;
        }
        land[i][j] = 1;
        int zeroCount = 1;
        for (int k = i - 1; k <= i + 1; k++) {
            for (int l = j - 1; l <= j + 1; l++) {
                zeroCount += dfsForSize(land, k, l);
            }
        }
        return zeroCount;
    }
    
    
    public static void main(String[] args) {
        int[][] land = new int[][]{{0, 2, 1, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}, {0, 1, 0, 1}};
        int[] result = new Interview_16_19_dfs().pondSizes(land);
        System.out.println("Arrays.toString(result) = " + Arrays.toString(result));
    }
}
